﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DimensionalMeasurement
{
    public partial class FormHistoricalData : Form
    {
        public FormHistoricalData()
        {
            InitializeComponent();
        }

        private void bClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void bMinimized_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Minimized;
        }

        private DateTime _startDate;
        private DateTime _endDate;
        private void bStart_Click(object sender, EventArgs e)
        {
            string strStartDate = dateStart.Text.Trim();
            string strEndDate = dateEnd.Text.Trim();
            if (!DateTime.TryParse(strStartDate, out _startDate))
            {
                _startDate = DateTime.MinValue;
            }
            if (!DateTime.TryParse(strEndDate, out _endDate))
            {
                _endDate = DateTime.MaxValue;
            }
            if (_startDate > _endDate)
            {
                DateTime datime = _startDate;
                _startDate = _endDate;
                _endDate = datime;
            }
            bStart.Text = "正在查询...";
            bStart.Enabled = false;
            //    btn_ExplortToExcell.Enabled = false;
            Task.Run(LoadHistory);

        }
        DataSet dsHistory;
        private void LoadHistory()
        {
            //sqlite数据库查询
            string strstarttime = _startDate.ToString("yyyy-MM-dd HH:mm:ss");
            string strendtime = _endDate.ToString("yyyy-MM-dd HH:mm:ss");

            dsHistory = GetHistorysSqLite(strstarttime, strendtime);
            dtSource = dsHistory.Tables[0];
            recordCount = dtSource.Rows.Count;
            pageCount = (recordCount / pageSize);
            if ((recordCount % pageSize) > 0)
            {
                pageCount++;
            }
            //默认第一页
            currentPage = 1;
            LoadPage();//调用加载数据的方法
        }
        public int pageSize = 10;      //每页记录数
        public int recordCount = 0;    //总记录数
        public int pageCount = 0;      //总页数
        public int currentPage = 0;    //当前页
        public bool UpPage = true;
        public bool NextPage = true;
        public bool DownPage = true;
        string result = "0";
        string Result = "0";
        DataTable dtSource = new DataTable();
        private void LoadPage()
        {
            int nCountOk = 0;
            int nCountNg = 0;
            if (currentPage < 1) currentPage = 1;
            if (currentPage > pageCount) currentPage = pageCount;

            int beginRecord;
            int endRecord;
            DataTable dtTemp;
            dtTemp = dtSource.Clone();

            beginRecord = pageSize * (currentPage - 1);
            if (currentPage == 1) beginRecord = 0;
            endRecord = pageSize * currentPage;

            endRecord = recordCount;
            if (dtSource.Rows.Count > 0)
            {
                for (int i = beginRecord; i < endRecord; i++)
                {
                    dtTemp.ImportRow(dtSource.Rows[i]);
                    DataRow row = (DataRow)dtSource.Rows[i];
                    if (row["是否合格"].ToString() == "0")
                    {
                        nCountOk++;
                    }
                }

                BeginInvoke(new Action(() =>
                {
                    dgvLeft.DataSource = dtTemp;  //datagridview控件名是tf_dgv1
                    DQ.Text = "当前页：" + currentPage.ToString();//当前页
                    ZYCount.Text = "总页数：" + pageCount.ToString();//总页数
                    JLCount.Text = "总记录数：" + recordCount.ToString();//总记录数
                    if (UpPage && NextPage && DownPage)
                    {
                        if (nCountOk > 0)
                        {
                            double percent = Convert.ToDouble(nCountOk) / Convert.ToDouble(recordCount);
                            result = string.Format("{0:0.00%}", percent);
                            Result = result;
                            lYield.Text = string.Format("{0}{1}", "合格率：", result);

                        }
                        else
                        {
                            lYield.Text = string.Format("{0}{1}", "合格率：", "0");
                        }
                    }
                    else
                    {
                        lYield.Text = string.Format("{0}{1}", "合格率：", Result);
                    }
                    bStart.Text = "开始查询";
                    bEccle.Enabled = true;
                    bStart.Enabled = true;
                    button1.Enabled = true;
                    button2.Enabled = true;
                    button3.Enabled = true;
                    button4.Enabled = true;
                }));
            }
            else
            {
                MessageBox.Show("当前时间段内无数据！");
                BeginInvoke(new Action(() =>
                {
                    bEccle.Enabled = true;
                    bStart.Enabled = true;
                    button1.Enabled = false;
                    button2.Enabled = false;
                    button3.Enabled = false;
                    button4.Enabled = false;
                    bStart.Text = "开始查询";
                }));

            }

        }

        /// <summary>
        /// 根据日前获取历史数据信息(sqlite)
        /// </summary>
        public DataSet GetHistorysSqLite(string startTime, string endTime)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("select iD,");
            strSql.Append("不良类型,");
            //if (PublicSet.JPWidthSwitch)
            //{
            //    strSql.Append("极片宽,");
            //}
            //if (PublicSet.JPTotalWidthSwitch)
            //{
            //    strSql.Append("极片总宽,");
            //}
            //if (PublicSet.JPLengthSwitch)
            //{
            //    strSql.Append("极片长,");
            //}
            //if (PublicSet.JEShoulderSwitch)
            //{
            //    strSql.Append("极耳肩宽,");
            //}
            //if (PublicSet.JEWidthSwitch)
            //{
            //    strSql.Append("极耳宽,");
            //}
            //if (PublicSet.JEHeightSwitch)
            //{
            //    strSql.Append("极耳高,");
            //}
            //if (PublicSet.DLHeightSwitch && PublicSet.PositiveSwitch)
            //{
            //    strSql.Append("陶瓷高,");
            //}
            //if (PublicSet.DLHeightSwitch && PublicSet.NegativeSwitch)
            //{
            //    strSql.Append("带料高,");
            //}
            //if (PublicSet.JECamearAngleSwitch)
            //{
            //    strSql.Append("极耳左相机角度,");
            //}
            //if (PublicSet.LeftCamearAngleSwitch)
            //{
            //    strSql.Append("左相机角度,");
            //}
            //if (PublicSet.RightCamearAngleSwitch)
            //{
            //    strSql.Append("右相机角度,");
            //}
            //if (PublicSet.JPCoatingSwitch)
            //{
            //    strSql.Append("涂布高,");
            //}
            //if (PublicSet.VAngleSwitch)
            //{
            //    strSql.Append("V1角度,");
            //    strSql.Append("V2角度,");
            //    strSql.Append("V3角度,");
            //}
            //if (PublicSet.VWidthSwitch)
            //{
            //    strSql.Append("V1宽度,");
            //    strSql.Append("V2宽度,");
            //    strSql.Append("V3宽度,");
            //}
            //if (PublicSet.VDepthSwitch)
            //{
            //    strSql.Append("V1深度,");
            //    strSql.Append("V2深度,");
            //    strSql.Append("V3深度,");
            //}
            strSql.Append("极片偏移X,");
            strSql.Append("极片偏移Y,");
            strSql.Append("极片偏移Z,");
            strSql.Append("是否合格,添加时间 ");
            strSql.Append(" FROM tb_jpjedis ");
            strSql.Append(string.Format(" WHERE 添加时间 between '{0}' and '{1}' ", startTime, endTime));
            try
            {
                return SQLiteHelper.Query(strSql.ToString());
            }
            catch (Exception ex)
            {
                Tool.LogForm("查询历史数据错误:" + ex.Message + " - " + ex.StackTrace);
            }
            return null;
        }





        private void FormHistoricalData_Load(object sender, EventArgs e)
        {

        }

        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            Tool.FormMove(Handle);
        }

        private void bClear_Click(object sender, EventArgs e)
        {
            if ((DataTable)dgvLeft.DataSource == null)
            {
                JLCount.Text = String.Format("{0}{1}", "总数量：", "0");
                lYield.Text = string.Format("{0}{1}", "合格率：", "0.00%");
            }
            else
            {
                DataTable dt = (DataTable)dgvLeft.DataSource;
                dt.Rows.Clear();
                dgvLeft.DataSource = dt;
                //dgvLeft.Rows.Clear();
                JLCount.Text = String.Format("{0}{1}", "总数量：", "0");
                lYield.Text = string.Format("{0}{1}", "合格率：", "0.00%");
                DQ.Text = "当前页：";
                ZYCount.Text = "总页数：";
                JLCount.Text = "总记录数：";
                button1.Enabled = false;
                button2.Enabled = false;
                button3.Enabled = false;
                button4.Enabled = false;
                UpPage = true;
                NextPage = true;
                DownPage = true;
            }
        }

        private void bEccle_Click(object sender, EventArgs e)
        {
            ExportDataGridViewToExcel(dgvLeft);
        }
        /// <summary>
        /// 导出EXCEL的方法
        /// </summary>
        /// <param name="dataGridview1"></param> 
        public static void ExportDataGridViewToExcel(DataGridView dataGridview1)
        {
            //"PDF文件|*.pdf|Word 2003文件|*.doc";Excel文件|*.xls
            try
            {
                if (dataGridview1.Rows.Count > 0)
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Filter = "*.xlsx|*.xlsx|*.CSV|*.CSV|*.xls|*.xls";
                    //  saveFileDialog.Filter = "txt  files  (*.txt)|*.txt";
                    saveFileDialog.FilterIndex = 0;
                    saveFileDialog.RestoreDirectory = true;
                    saveFileDialog.CreatePrompt = true;
                    saveFileDialog.Title = "导出Excel文件到";
                    DateTime now = DateTime.Now;
                    saveFileDialog.FileName = now.Year.ToString().PadLeft(2) + now.Month.ToString().PadLeft(2, '0') + now.Day.ToString().PadLeft(2, '0') + "-" + now.Hour.ToString().PadLeft(2, '0') + now.Minute.ToString().PadLeft(2, '0') + now.Second.ToString().PadLeft(2, '0');
                    DialogResult Result = saveFileDialog.ShowDialog();
                    if (Result == DialogResult.Cancel) //取消导出操作的处理
                    {
                        return;
                    }
                    StreamWriter sw;
                    Stream myStream;
                    myStream = saveFileDialog.OpenFile();
                    sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
                    string str = "";
                    try
                    {
                        //写标题    
                        for (int i = 0; i < dataGridview1.ColumnCount; i++)
                        {
                            if (i > 0)
                            {
                                str += "\t";
                            }
                            str += dataGridview1.Columns[i].HeaderText;
                        }
                        sw.WriteLine(str);
                        //写内容 
                        for (int j = 0; j < dataGridview1.Rows.Count - 1; j++)
                        {
                            string tempStr = "";
                            for (int k = 0; k < dataGridview1.Columns.Count; k++)
                            {
                                if (k > 0)
                                {
                                    tempStr += "\t";
                                }
                                tempStr += dataGridview1.Rows[j].Cells[k].Value.ToString();
                            }
                            sw.WriteLine(tempStr);
                        }
                    }
                    catch (Exception e)
                    {
                        // MessageBox.Show(e.ToString());
                    }
                    finally
                    {
                        sw.Close();
                        myStream.Close();
                        MessageBox.Show("导出成功！");
                    }
                }
                else
                {
                    MessageBox.Show("没有数据可供导出！", "警告", MessageBoxButtons.OK);
                    return;
                }
            }
            catch
            {
                MessageBox.Show("导出数据出错，请重新操作！", "提示", MessageBoxButtons.OK);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            currentPage = 1;
            LoadPage();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            currentPage--;
            UpPage = false;
            LoadPage();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            currentPage++;
            NextPage = false;
            LoadPage();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            currentPage = pageCount;
            DownPage = false;
            LoadPage();
        }
    }
}
